package com.xyh.system.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xyh.system.model.Menu;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author xyh
 * @since 2020-12-30
 */
@Repository
public interface MenuMapper extends BaseMapper<Menu> {

    @Select("select distinct menu.menu_id," +
            "   menu.parent_id," +
            "   menu.menu_name," +
            "   menu.url," +
            "   menu.perms," +
            "   menu.order_num," +
            "   menu.icon " +
            "   from    user," +
            "           role," +
            "           user_role," +
            "           menu," +
            "           role_menu " +
            "        where user.user_id = user_role.user_id " +
            "          and role.role_id = user_role.role_id " +
            "          and role.role_id = role_menu.role_id " +
            "          and menu.menu_id = role_menu.menu_id " +
            "          and user.username = #{username}")
    @ResultMap(value = "com.xyh.system.mapper.MenuMapper.menuMap")
    List<Menu> selectMenuByUserName(@Param("username") String username);

    /*
     * 直接子查询查出所有菜单树
     */
    List<Menu> selectAllTree();

    /*
     * 通过parentId查询父级菜单下的所以子集菜单
     */
    @Select("SELECT menu_id, parent_id, menu_name, url, perms, order_num, create_time, modify_time, icon " +
            "FROM menu WHERE parent_id = #{parentId} ORDER BY order_num")
    List<Menu> selectChildMenuByParentId(Integer parentId);

    /**
     * 查询带功能权限的菜单树,并组装根节点
     *
     * @return Menu菜单树集合
     */
    List<Menu> selectAllMenuAndCountOperator();

    /**
     * 调整菜单排序
     *
     * @param currentId 需要调整的菜单id
     * @param swapId    与之交换的菜单id
     */
    void swapSort(@Param("currentId") Integer currentId, @Param("swapId") Integer swapId);

    /**
     * 获取排序字段的最大值
     *
     * @return 排序字段的最大值
     * ifnull(查询语句，默认值)：就是若查询语句查询的结果为空，则返回默认值！
     */
    @Select("SELECT IFNULL(MAX(order_num),0) " +
            "FROM menu")
    Integer selectMaxOrderNum();

    /**
     * 删除菜单节点，如果存在下级节点则一并删除
     *
     * @param menuId
     * @return
     */
    @Delete("DELETE " +
            "FROM menu WHERE menu_id = #{menuId} or parent_id = #{menuId}")
    Integer removeByParentIdEqMenuId(Integer menuId);
}

